package com.horatio.Thread;

import java.lang.Thread.UncaughtExceptionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PriorityThreadFactory implements ThreadFactory {

	/**
	 * 线程优先级
	 */
	private int prio;
	
	/**
	 * 线程名称
	 */
	private String name;
	
	/**
	 * 线程条数
	 */
	private AtomicInteger	threadNumber	= new AtomicInteger(1);
	
	/**
	 * 线程组
	 */
	private ThreadGroup		group;
	
	private static final Logger log = LoggerFactory.getLogger(UncaughtExceptionHandler.class);
	
	public PriorityThreadFactory(String name, int normPriority) 
	{
		this.name = name;
		this.prio = normPriority;
		this.group = new ThreadGroup(this.name);
	}

	@Override
	public Thread newThread(Runnable r) 
	{
		Thread t = new Thread(group, r);
		t.setName(name + "-" + threadNumber.getAndIncrement());
		t.setPriority(prio);
		t.setUncaughtExceptionHandler
		(
			new UncaughtExceptionHandler()
			{
				@Override
				public void uncaughtException(Thread t, Throwable e) 
				{
					log.error("严重错误 - 线程: " + t.getName() + " 终止异常 " + e, e);
					if (e instanceof OutOfMemoryError)
					{
						// TODO try get some memory or restart
						log.error("内存不足! 需要更多的内存!");
					}
				}
			}
		);
		return t;
	}

}
